package com.vnp.vchat;

import net.appkraft.parallax.ParallaxScrollView;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap.Config;
import android.graphics.Bitmap;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.Window;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.android.gcm.GCMRegistrar;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageLoadingListener;
import com.vnp.vchat.Util.KeyboardHelper;
import com.vnp.vchat.Util.PreferenceHelper;
import com.vnp.vchat.Util.Utils;
import com.vnp.vchat.database.MySQLiteHelper;
import com.vnp.vchat.httpclient.HttpClientHelper;
import com.vnp.vchat.httpclient.MyJsonHttpResponseHandler;
import com.vnp.vchat.version2.SplashScreenActivity;

public class CaidatActivity extends Activity implements OnTouchListener, OnClickListener {

	TextView title, title_thongbao, title_tinnhan, title_hoatdong, title_hienthi,
			title_dangxuat, title_taikhoan, title_hienthi_tn;
	ImageButton btnOnOffTinnhan, btnOnOffHoatdong, btnOnOffHienthi;

	// settings
	int notification_tinnhan;
	int notification_hoatdong;
	int notification_hienthi;
	
	PreferenceHelper preferenceHelper;
	ImageView image;
	ParallaxScrollView parallax;
	
	int state;
	
	ViewGroup btnDangxuat;
	
	DisplayImageOptions options = new DisplayImageOptions.Builder()
									.cacheInMemory(false).cacheOnDisc(true)
									.bitmapConfig(Config.RGB_565)
									.build();
	TextView txtName;
	
	MySQLiteHelper db;
	
	Dialog dThoat;
	Runnable r = new Runnable() {
		
		@Override
		public void run() {
			gotoLogin();
		}
	};
	
	Runnable rS = new Runnable() {
		
		@Override
		public void run() {
			if (state == 1) {
				if (notification_tinnhan == 1){
					notification_tinnhan = 0;
					btnOnOffTinnhan.setImageResource(R.drawable.btn_off);
				} else if (notification_tinnhan == 0) {
					notification_tinnhan = 1;	
					btnOnOffTinnhan.setImageResource(R.drawable.btn_on);
				}
				
				preferenceHelper.setSettingNotifi(String.valueOf(notification_tinnhan));
				
			} else if (state ==2) {
				if (notification_hoatdong == 1){
					notification_hoatdong = 0;
					btnOnOffHoatdong.setImageResource(R.drawable.btn_off);
				} else if (notification_hoatdong == 0) {
					notification_hoatdong = 1;	
					btnOnOffHoatdong.setImageResource(R.drawable.btn_on);
				}
				
				preferenceHelper.setSettingFeed(String.valueOf(notification_hoatdong));
				
			} else if (state ==3) {
				if (notification_hienthi == 1){
					notification_hienthi = 0;
					btnOnOffHienthi.setImageResource(R.drawable.btn_off);
				} else if (notification_hienthi == 0) {
					notification_hienthi = 1;	
					btnOnOffHienthi.setImageResource(R.drawable.btn_on);
				}
				
				preferenceHelper.setSettingDisplay(String.valueOf(notification_hienthi));
			}
		}
	};
	
	Handler mHandler = new Handler();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_scrollview);
		preferenceHelper = new PreferenceHelper(this);
		db = new MySQLiteHelper(this);
		
		notification_tinnhan = Integer.parseInt(preferenceHelper.getSettingNotifi());
		notification_hoatdong = Integer.parseInt(preferenceHelper.getSettingFeed());
		notification_hienthi = Integer.parseInt(preferenceHelper.getSettingDisplay());
		
		
		title = (TextView) findViewById(R.id.title);
		
		txtName = (TextView) findViewById(R.id.txt_name);
		
		parallax = (ParallaxScrollView) findViewById(R.id.scrollView1);
		image = (ImageView) findViewById(R.id.imageView1);
		parallax.setImageViewToParallax(image);
		image.setImageResource(R.drawable.no_avatar);
		runOnUiThread(new Runnable() {
			
			@Override
			public void run() {
				ImageLoader.getInstance().displayImage(preferenceHelper.getMyAvatar(), image, options, new ImageLoadingListener() {
					
					@Override
					public void onLoadingStarted(String imageUri, View view) {
						
					}
					
					@Override
					public void onLoadingFailed(String imageUri, View view,
							FailReason failReason) {
						Log.i("vChat", "load anh ko dc");
						image.setImageResource(R.drawable.no_avatar);
					}
					
					@Override
					public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
						
					}
					
					@Override
					public void onLoadingCancelled(String imageUri, View view) {
						
					}
				});
			}
		});
		
		
		title_thongbao = (TextView) findViewById(R.id.title_thongbao);
		title_tinnhan = (TextView) findViewById(R.id.title_tinnhan);
		title_hoatdong = (TextView) findViewById(R.id.title_hoatdong);
		title_dangxuat = (TextView) findViewById(R.id.title_dangxuat);
		title_taikhoan = (TextView) findViewById(R.id.title_taikhoan);
		title_hienthi = (TextView) findViewById(R.id.title_hienthi);
		title_hienthi_tn = (TextView) findViewById(R.id.title_hienthi_tn);
		
		btnDangxuat = (ViewGroup) findViewById(R.id.btn_dangxuat);

		btnOnOffTinnhan = (ImageButton) findViewById(R.id.btn_on_off_tinnhan);
		btnOnOffHoatdong = (ImageButton) findViewById(R.id.btn_on_off_hoatdong);
		btnOnOffHienthi = (ImageButton) findViewById(R.id.btn_on_off_hienthi);

		showStateButton();
		setFont();
		init();
		
		btnDangxuat.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				showDialogThoat();
			}
		});
	}
	
	void showStateButton(){
		title.setText(preferenceHelper.getUserName());
		txtName.setText(preferenceHelper.getUserName());
		
		
		if (notification_tinnhan == 1){
			btnOnOffTinnhan.setImageResource(R.drawable.btn_on);
		} else {
			btnOnOffTinnhan.setImageResource(R.drawable.btn_off);
		}
		
		if (notification_hoatdong == 1){
			btnOnOffHoatdong.setImageResource(R.drawable.btn_on);
		} else if(notification_hoatdong == 0){
			btnOnOffHoatdong.setImageResource(R.drawable.btn_off);
		}
		
		
		
		if (notification_hienthi == 1){
			btnOnOffHienthi.setImageResource(R.drawable.btn_on);
		} else {
			btnOnOffHienthi.setImageResource(R.drawable.btn_off);
		}
		
	}

	private void setFont() {
//		title.setTypeface(Utils.getTypefaceBold(CaidatActivity.this));
		title_thongbao.setTypeface(Utils.getTypefaceMedium(CaidatActivity.this));
		title_tinnhan.setTypeface(Utils.getTypefaceRegular(CaidatActivity.this));
		title_hoatdong.setTypeface(Utils.getTypefaceRegular(CaidatActivity.this));
		title_dangxuat.setTypeface(Utils.getTypefaceRegular(CaidatActivity.this));
		title_hienthi_tn.setTypeface(Utils.getTypefaceRegular(CaidatActivity.this));
		title_taikhoan.setTypeface(Utils.getTypefaceMedium(CaidatActivity.this));
		txtName.setTypeface(Utils.getTypefaceBold(CaidatActivity.this));
	}

	private void init() {
		btnOnOffHoatdong.setOnTouchListener(this);
		btnOnOffTinnhan.setOnTouchListener(this);
		btnOnOffHienthi.setOnTouchListener(this);
		title_dangxuat.setOnTouchListener(this);
	}


	@Override
	public boolean onTouch(View v, MotionEvent event) {
		switch (v.getId()) {
		case R.id.btn_on_off_tinnhan:
			if (event.getAction() == MotionEvent.ACTION_UP) {
				state = 1;
				if (notification_tinnhan == 0) {
					notification_tinnhan = 1;
					postSettings(notification_tinnhan, notification_hoatdong, notification_hienthi);
					btnOnOffTinnhan.setImageResource(R.drawable.btn_on);
				} else {
					notification_tinnhan = 0;
					postSettings(notification_tinnhan, notification_hoatdong, notification_hienthi);
					btnOnOffTinnhan.setImageResource(R.drawable.btn_off);
				}
			}
			break;

		case R.id.btn_on_off_hoatdong:
			if (event.getAction() == MotionEvent.ACTION_UP) {
				state = 2;
				if (notification_hoatdong == 0) {
					notification_hoatdong = 1;
					postSettings(notification_tinnhan, notification_hoatdong, notification_hienthi);
					btnOnOffHoatdong.setImageResource(R.drawable.btn_on);
				} else {
					notification_hoatdong = 0;
					postSettings(notification_tinnhan, notification_hoatdong, notification_hienthi);
					btnOnOffHoatdong.setImageResource(R.drawable.btn_off);
				}
			}
			break;
		case R.id.btn_on_off_hienthi:
			if (event.getAction() == MotionEvent.ACTION_UP) {
				state = 3;
				if (notification_hienthi == 0) {
					notification_hienthi = 1;
					postSettings(notification_tinnhan, notification_hoatdong, notification_hienthi);
					btnOnOffHienthi.setImageResource(R.drawable.btn_on);
				} else {
					notification_hienthi = 0;
					postSettings(notification_tinnhan, notification_hoatdong, notification_hienthi);
					btnOnOffHienthi.setImageResource(R.drawable.btn_off);
				}
			}
			break;
		
		case R.id.btn_dangxuat:
			if (event.getAction() == MotionEvent.ACTION_UP) {
//				new DangxuatAsynTask().execute("");
				gotoLogin();
			}
		break;
	}
		return false;
	}
	
	void postSettings(final int st_notifi, final int st_feed, final int st_display){
		HttpClientHelper httpClientHelper = new HttpClientHelper(new MyJsonHttpResponseHandler(){

			@Override
			public void onFailure(Throwable error) {
				super.onFailure(error);
				mHandler.removeCallbacks(rS);
				mHandler.postDelayed(rS, 1000);
			}

			@Override
			public void onSuccess(JSONObject re) {
				
				Log.i("vChat", "Re: "+re.toString());
				try {
					int status = re.getInt("status");
					if (status == 1){
						Log.i("vChat", "Cap nhat thanh cong");
						preferenceHelper.setSettingNotifi(String.valueOf(st_notifi));
						preferenceHelper.setSettingFeed(String.valueOf(st_feed));
						preferenceHelper.setSettingDisplay(String.valueOf(st_display));
					} else {
						mHandler.removeCallbacks(rS);
						mHandler.postDelayed(rS, 1000);
						Log.i("vChat", "Cap nhat that bai");
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
			
		});
		
		httpClientHelper.postSettings(preferenceHelper.getUserId(), preferenceHelper.getHash(), st_notifi, st_feed, st_display);
		
	}
	
	/*private class DangxuatAsynTask extends AsyncTask<String, Void, String>{

		@Override
		protected String doInBackground(String... params) {
			xoaCookies();
			return "";
		}

		@Override
		protected void onPostExecute(String result) {
		}

		@Override
		protected void onProgressUpdate(Void... values) {
			
		}
		

	}*/
	
	private void gotoLogin(){
		xoaCookies();
		MainActivity.isExit = false;
		Intent c = new Intent(CaidatActivity.this,SplashScreenActivity.class);
		finish();
		c.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		startActivity(c);
	}
	
	private void xoaCookies(){
//		MainActivity.isExit = false;
		Log.i("DATA", "DA nhay vao xoa cookies");
		 CookieSyncManager.createInstance(this); 
		 CookieManager cookieManager = CookieManager.getInstance();
		 cookieManager.removeAllCookie();
		 cookieManager.removeExpiredCookie();
		 cookieManager.removeSessionCookie();
		 preferenceHelper.setUserId("");
		 preferenceHelper.setDataJoin("");
		 preferenceHelper.setAvatarKH("");
		 preferenceHelper.setDeviceId("");
		 preferenceHelper.setMyAvatar("");
		 preferenceHelper.setUserName("");
		 preferenceHelper.setSettingFeed("");
		 preferenceHelper.setSettingDisplay("");
		 preferenceHelper.setSettingNotifi("");
		 preferenceHelper.setDomainConnect("");
		 preferenceHelper.setPostConnect("");
		 db.deleteAllKH();
		 db.deleteHisChat();
//		 unregisterGCM();
	}
	
	void showDialogThoat(){
		dThoat = new Dialog(this);
		dThoat.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dThoat.setContentView(R.layout.dialog_thoat_tk);
		
		
		TextView txtThoat = (TextView) dThoat.findViewById(R.id.str_canhbao_thoat);
		
		Button btnThoat = (Button) dThoat.findViewById(R.id.btn_thoat_tk);
		Button btnKo = (Button) dThoat.findViewById(R.id.btn_ko);
		dThoat.show();
		dThoat.getWindow().setBackgroundDrawable(new ColorDrawable(0));
		dThoat.setCanceledOnTouchOutside(true);
		dThoat.getWindow().setGravity(Gravity.CENTER);
		dThoat.show();
		
		txtThoat.setTypeface(Utils.getTypefaceRegular(CaidatActivity.this), Typeface.BOLD);
		btnThoat.setTypeface(Utils.getTypefaceRegular(CaidatActivity.this), Typeface.BOLD);
		btnKo.setTypeface(Utils.getTypefaceRegular(CaidatActivity.this), Typeface.BOLD);
		// setonclick
		btnThoat.setOnClickListener(this);
		btnKo.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_thoat_tk:
			dThoat.dismiss();
			mHandler.removeCallbacks(r);
			mHandler.postDelayed(r, 300);
			break;
		case R.id.btn_ko:
			dThoat.dismiss();
			break;

		default:
			break;
		}
	}

	@Override
	protected void onPause() {
		super.onPause();
		mHandler.removeCallbacks(r);
		mHandler.removeCallbacks(rS);
	}
	
	
	@Override
	protected void onResume() {
		super.onResume();
		KeyboardHelper.hideSoftKeyboard(CaidatActivity.this);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		mHandler.removeCallbacks(r);
		mHandler.removeCallbacks(rS);
		mHandler.removeCallbacksAndMessages(null);
	}
	
	public void unregisterGCM(){
		try {
			GCMRegistrar.onDestroy(CaidatActivity.this);
			GCMRegistrar.unregister(CaidatActivity.this);	
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	
	
	
}
